<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace hdphp\services;

use think\exception\ValidateException;
use think\Image;

/**
 * Class：DownloadImageService
 * 创建人：Jack
 * 创建时间：2023/11/25 8:41
 * @package hdphp
 */
class DownloadImageService
{
    // 是否生成缩略图
    protected $thumb = false;
    // 缩略图宽度
    protected $thumbWidth = 300;
    // 缩略图高度
    protected $thumHeight = 300;
    // 存储位置
    protected $path = 'attach';

    protected $rules = ['thumb', 'thumbWidth', 'thumHeight', 'path'];

    /**
     * 注释：获取即将要下载的图片扩展名
     * 创建人：Jack
     * 创建时间：2023/11/25 8:43
     * @param string $url
     * @param string $ex
     * @return array
     */
    public function getImageExtname(string $url = '', string $ex = 'jpg')
    {
        $_empty = ['file_name' => '', 'ext_name' => $ex];
        if (!$url) return $_empty;
        if (strpos($url, '?')) {
            $_tar = explode('?', $url);
            $url = trim($_tar[0]);
        }
        $arr = explode('.', $url);
        if (!is_array($arr) || count($arr) <= 1) return $_empty;
        $ext_name = trim($arr[count($arr) - 1]);
        $ext_name = !$ext_name ? $ex : $ext_name;
        return ['file_name' => md5($url) . '.' . $ext_name, 'ext_name' => $ext_name];
    }

    /**
     * 注释：下载图片
     * 创建人：Jack
     * 创建时间：2023/11/25 8:44
     * @param string $url
     * @param string $name
     * @return array
     */
    public function downloadImage(string $url, string $name = '')
    {
        if (!$name) {
            // 获取要下载的文件名称
            $downloadImageInfo = $this->getImageExtname($url);
            $ext = $downloadImageInfo['ext_name'];
            $name = $downloadImageInfo['file_name'];
            if (!$name) throw new ValidateException('上传图片不存在!');
        } else {
            $ext = $this->getImageExtname($name)['ext_name'];
        }
        if (!in_array($ext, ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bpm', 'tif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'apng'])) {
            $headerArray = get_headers(str_replace('\\', '/', $url), true);
            if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Type']) == 2) {
                $type = $headerArray['Content-Type'][1];
            } else {
                $type = $headerArray['Content-Type'];
            }
            if (!$type) throw new ValidateException('格式错误，文件后缀不允许!');
            $img = explode('/', $type);
            if ($img[0] != 'image') throw new ValidateException('格式错误，文件后缀不允许!');
        }
        if (strstr($url, 'http://') === false && strstr($url, 'https://') === false) {
            $url = 'http:' . $url;
        }
        $url = str_replace('https://', 'http://', $url);
        if ($this->path == 'attach') {
            $date_dir = date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d');
            $to_path = $this->path . '/' . $date_dir;
        } else {
            $to_path = $this->path;
        }
        $upload = UploadService::init(1);
        if (!file_exists($upload->uploadDir($to_path) . '/' . $name)) {
            ob_start();
            readfile($url);
            $content = ob_get_contents();
            ob_end_clean();
            $size = strlen(trim($content));
            if (!$content || $size <= 2) throw new ValidateException('图片流获取失败!');
            if ($upload->to($to_path)->down($content, $name) === false) {
                throw new ValidateException('图片下载失败!');
            }
            $imageInfo = $upload->getDownloadInfo();
            $path = $imageInfo['dir'];
            if ($this->thumb) {
                Image::open(root_path() . 'public' . $path)->thumb($this->thumbWidth, $this->thumHeight)->save(root_path() . 'public' . $path);
                $this->thumb = false;
            }
        } else {
            $path = '/uploadfile/' . $to_path . '/' . $name;
            $imageInfo['name'] = $name;
        }
        $date['path'] = $path;
        $date['name'] = $imageInfo['name'];
        $date['size'] = $imageInfo['size'] ?? '';
        $date['mime'] = $imageInfo['type'] ?? '';
        $date['image_type'] = 1;
        $date['is_exists'] = false;
        $date['md5file'] = $imageInfo['md5file'] ?? '';
        $date['ip'] = $imageInfo['ip'] ?? '';
        return $date;
    }

    /**
     * 注释：__call
     * 创建人：Jack
     * 创建时间：2023/11/25 8:42
     * @param $name
     * @param $arguments
     * @return $this
     */
    public function __call($name, $arguments)
    {
        if (in_array($name, $this->rules)) {
            if ($name === 'path') {
                $this->{$name} = $arguments[0] ?? 'attach';
            } else {
                $this->{$name} = $arguments[0] ?? null;
            }
            return $this;
        } else {
            throw new \RuntimeException('Method does not exist' . __CLASS__ . '->' . $name . '()');
        }
    }
}